package controller

import (
	"fmt"
	"github.com/mjiulee/lego"
	"saas_sys_base/common"

	"strconv"

	//"github.com/mjiulee/lego/utils"
	"github.com/valyala/fasthttp"

	. "saas_sys_base/modules/adminSaas/service"
	appmanagerService "saas_sys_base/modules/appmanager/service"
	. "saas_sys_base/modules/system/service"
	. "saas_sys_base/modules/tenant/service"
	userService "saas_sys_base/modules/user/service"
)


func init() {
	vc := new(AdminSaasHomeViewCtrl)
	_ctrlList = append(_ctrlList, vc)

}




/* ************************************************************************************ */
/* 类型定义 */
type AdminSaasHomeViewCtrl struct {
	service     AdminSaasHomeService
	userService SysUserService //注意，这里还是使用system模块的用户，后台管理用户还是用system上的管理用户数据

	tenantService TenantService
	appTenantPermissionService appmanagerService.AppTenantPermissionService
	appmanagerService appmanagerService.AppManagerService
	appTenantUserRelService userService.AppTenantUserRelService
}

func (vc *AdminSaasHomeViewCtrl) CtrlInfo() string {
	return "AdminSaasHomeViewCtrl"
}

func (vc *AdminSaasHomeViewCtrl) RoutInit() {

	// TODO 与sys模块url重复，后续根据需求修改 lego.GET("/", vc.Index, lego.LEGO_SESSION_TYPE_ADMIN, true)
	lego.GET("/adminSaas/home/index", vc.Index, lego.LEGO_SESSION_TYPE_ADMIN, true) //租户管理端
	lego.GET("/adminSaas/home_app/index", vc.IndexForApp, lego.LEGO_SESSION_TYPE_ADMIN, true) //app管理端
	lego.GET("/adminSaas/home/console", vc.Console, lego.LEGO_SESSION_TYPE_ADMIN, false)
	lego.POST("/adminSaas/home/initmenu", vc.InitMenu, lego.LEGO_SESSION_TYPE_ADMIN, false)
}

/* 首页
 * params:
 */
func (vc *AdminSaasHomeViewCtrl) Index(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		sessionData := common.GetSessionData(&ctxExt)
		appwho := sessionData.AppTokenWho

		// 获取平台菜单 资源
		//userid := lego.SessionGetKeyIntVal("user_id", ctx)
		userid, _ := strconv.ParseInt(lego.SessionGetKeyVal("user_id", ctx).(string), 10, 64)
		user, profile := vc.userService.GetSysUserById(userid)
		if user == nil {
			ctxExt.ResponseWithStateCode200(100,
				fmt.Sprintf("this sys admin user isnot exist, <uid: %d>", userid))
			ctx.Redirect("/admin/login", 302)
			return
		}
		data["UserName"] = profile.UserName
		menus := vc.service.GetUserRoleMenu(appwho, user, profile, common.MenuMode_Tenant)
		data["menus"] = menus
		data["Who"] = appwho


		appTenantPermission := vc.appTenantPermissionService.GetAppTenantPermissionByWho(appwho) //这条检查tid为0时是进不来的
		//hasPermission, _ := vc.appmanagerService.CheckAppTenantPermission(appwho)
		if appTenantPermission == nil {
		//if !hasPermission {
			ctxExt.ResponseWithStateCode200(100,
				    fmt.Sprintf("this tenant isnot exist, <tid: %d, appid: %d, uid: %d>",
				                                       appwho.TenantId,
				                                       appwho.MiniAppId,
				                                       appwho.Uid))
			return
		}

		_, token, err := vc.appTenantUserRelService.UserLogin(appwho)
		if err != nil {
			ctxExt.ResponseWithStateCode200(100,
				                             fmt.Sprintf("ERR: %s,  NO PERMISSION<tid: %d, appid: %d, uid: %d>",
				                             	err.Error(),
				                                appwho.TenantId,
				                                appwho.MiniAppId,
				                                appwho.Uid))
			return
		}

		data["Token"] = token
		break
	}
	ctxExt.HTML("adminSaas/view/Home/home.html", data)
	return
}

/* 首页
 * params:
 */
func (vc *AdminSaasHomeViewCtrl) IndexForApp(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		sessionData := common.GetSessionData(&ctxExt)
		appwho := sessionData.AppTokenWho

		// 获取平台菜单 资源
		//userid := lego.SessionGetKeyIntVal("user_id", ctx)
		userid, _ := strconv.ParseInt(lego.SessionGetKeyVal("user_id", ctx).(string), 10, 64)
		user, profile := vc.userService.GetSysUserById(userid)
		if user == nil {
			ctxExt.ResponseWithStateCode200(100,
				fmt.Sprintf("this sys admin user isnot exist, <uid: %d>", userid))
			ctx.Redirect("/admin/login", 302)
			return
		}
		data["UserName"] = profile.UserName
		menus := vc.service.GetUserRoleMenu(appwho, user, profile, common.MenuMode_MiniApp)
		data["menus"] = menus
		data["Who"] = appwho

		//appTenantPermission := vc.appTenantPermissionService.GetAppTenantPermissionByWho(appwho)

		hasPermission, _ := vc.appmanagerService.CheckAppPermission(appwho)
		//hasPermission, err := vc.appmanagerService.CheckAppTenantPermission(*appwho)
		//if appTenantPermission == nil {
		if !hasPermission {
			ctxExt.ResponseWithStateCode200(100,
				fmt.Sprintf("no permission for app, <tid: %d, appid: %d, uid: %d>",
					appwho.TenantId,
					appwho.MiniAppId,
					appwho.Uid))
			return
		}

		_, token, err := vc.appTenantUserRelService.UserLogin(appwho)
		if err != nil {
			ctxExt.ResponseWithStateCode200(100,
				fmt.Sprintf("ERR: %s,  NO PERMISSION<tid: %d, appid: %d, uid: %d>",
					err.Error(),
					appwho.TenantId,
					appwho.MiniAppId,
					appwho.Uid))
			return
		}

		data["Token"] = token
		break
	}
	ctxExt.HTML("adminSaas/view/Home/home_app.html", data)
	return
}

/* 首页
 * params:
 */
func (vc *AdminSaasHomeViewCtrl) Console(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		// 统计订单信息
		data["user_today"] = vc.service.GetTodayNewUser()
		data["user_total"] = vc.service.GetTotalUser()

		data["driver_online"] = vc.service.GetOnLineDriver()
		data["driver_total"] = vc.service.GetTotaldriver()

		data["order_today"] = vc.service.GetTodayOrder()
		data["order_total"] = vc.service.GetTotalOrder()

		data["locations"] = vc.service.GetDriverLocations()
		break
	}
	ctxExt.HTML("adminSaas/view/Home/console.html", data)
	return
}

/* 首页
 * params:
 */
func (vc *AdminSaasHomeViewCtrl) InitMenu(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	code := 0
	msg := "success"

	for {
		// 统计订单信息
		err := vc.service.InitMenu()
		if err != nil {
			code = -1
			msg = err.Error()
		}
		break
	}
	response["code"] = code
	response["msg"] = msg
	ctxExt.JSON(200, response)
	return
}
